﻿using System;
using System.Linq;
using System.Reflection;
using FastColoredTextBoxNS;
using System.Collections.Generic;
/// <summary>
/// Builds list of methods and properties for current class name was typed in the textbox
/// </summary>
internal class DynamicCollection : IEnumerable<AutocompleteItem>
{
    /// <summary>
    /// Menu
    /// </summary>
    private AutocompleteMenu menu;
    /// <summary>
    /// FastColoredTextBox
    /// </summary>
    private FastColoredTextBox tb;
    /// <summary>
    /// Default Constructor
    /// </summary>
    /// <param name="menu"></param>
    /// <param name="tb"></param>
    public DynamicCollection(AutocompleteMenu menu, FastColoredTextBox tb)
    {
        this.menu = menu;
        this.tb = tb;
    }
    /// <summary>
    /// Gets Enumerator
    /// </summary>
    /// <returns></returns>
    public IEnumerator<AutocompleteItem> GetEnumerator()
    {
        //get current fragment of the text
        var text = menu.Fragment.Text;

        //extract class name (part before dot)
        var parts = text.Split('.');
        if (parts.Length < 2)
            yield break;
        var className = parts[parts.Length - 2];

        //find type for given className
        var type = FindTypeByName(className);

        if (type == null)
            yield break;

        //return static methods of the class
        foreach (var methodName in type.GetMethods().AsEnumerable().Select(mi => mi.Name).Distinct())
            yield return new MethodAutocompleteItem(methodName + "()");

        //return static properties of the class
        foreach (var pi in type.GetProperties())
            yield return new MethodAutocompleteItem(pi.Name);
    }
    /// <summary>
    /// Finds Type By Name
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    Type FindTypeByName(string name)
    {
        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
        Type type = null;
        foreach (var a in assemblies)
        {
            foreach (var t in a.GetTypes())
                if (t.Name == name)
                {
                    return t;
                }
        }

        return null;
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}